import time
import pandas as pd
import datetime
import re
import requests
import yaml
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# 读取配置文件
with open('config.yaml', 'r', encoding='utf-8') as config_file:
    config = yaml.safe_load(config_file)

AUTHORIZATION = config["Authorization"]
TABLE_ID_MAIL = config["AddMail"]["table_id_mail"]
FIELD_2200000447328061 = config["AddMail"]["field_2200000447328061"]
TABLE_ID_ORDER = config["AddOrder"]["table_id_order"]

# 请求头
headers = {
    "Authorization": AUTHORIZATION,
    "Content-Type": "application/json",
    # 可根据需要添加其他请求头信息
}

# 读取Excel文件
xls = pd.ExcelFile("AppleMail.xls")

# 读取 迅果 和 收卡商 表格
xunguo_data = xls.parse("迅果")
shoukashang_data = xls.parse("收卡商")


def add_mail(email, password, file):
    # 请求URL
    url_addMail = "https://api.huoban.com/paas/hbdata/item"
    # 创建请求数据
    data = {
        "table_id": TABLE_ID_MAIL,
        "fields": {
            "2200000447328055": email,
            "2200000447328056": password,
            "2200000447328057": "",
            "2200000447328058": "",
            "2200000447328059": "",
            "2200000447328060": "",
            "2200000447328061": FIELD_2200000447328061,
            "2200000447328062": "",
            "2200000447328063": "",
            "2200000447328064": None,
            "2200000447328065": []
        },
        "location": "item",
        "second_confirmation": False
    }

    # 发送POST请求
    response = requests.post(url_addMail, json=data, headers=headers, verify=False)
    response_data = response.json()
    message = response_data.get("message")
    try:
        # 检查响应
        if response.status_code == 200 and message == "success":
            print(f"邮箱创建成功：邮箱 {email}，密码 {password}")
        elif response.status_code == 500 and message == "邮箱已存在重复数据":
            print(f"邮箱 {email}已存在，无需创建")
    except Exception:
        file.write(
            f"{datetime.datetime.now()}:创建邮箱请求异常：邮箱 {email}，密码 {password}，响应消息：{message}\n")


def add_order(email, code, money, exchange_rate, operator, file):
    # 获取默认值
    url_b = f'https://api.huoban.com/paas/hbdata/table/{TABLE_ID_ORDER}/get_default_value'
    response_b = requests.get(url_b, headers=headers, verify=False)
    data_b = response_b.json()
    param_2200000447328066 = data_b['data']['fields']['2200000447328066']
    param_2200000447328067 = data_b['data']['fields']['2200000447328067']

    # 获取邮箱ID，通过邮箱名
    url_c = f'https://api.huoban.com/paas/hbdata/item/field/2200000447328068/search_relation'
    data_c = {
        "text": "",
        "offset": 0,
        "limit": 50,
        "table_id": TABLE_ID_ORDER,
        "related_fields": {},
        "recommend_filter": False
    }
    response_c = requests.post(url_c, json=data_c, headers=headers, verify=False)
    data_c = response_c.json()

    # 提取item_id
    item_id = None
    for item in data_c['data']['items']:
        if item['title'] == email:
            item_id = item['item_id']
            break

    # 创建订单
    data_a = {
        "table_id": TABLE_ID_ORDER,
        "fields": {
            "2200000447328066": param_2200000447328066,
            "2200000447328067": param_2200000447328067,
            "2200000447328068": [item_id],
            "2200000447328069": code,
            "2200000447328070": money,
            "2200000447328071": exchange_rate,
            "2200000447328072": "",
            "2200000447567612": operator
        },
        "location": "item",
        "second_confirmation": False
    }

    # 请求A - 发送创建订单的POST请求
    url_a = 'https://api.huoban.com/paas/hbdata/item'

    # 发送POST请求
    response_a = requests.post(url_a, json=data_a, headers=headers, verify=False)
    response_data = response_a.json()
    message = response_data.get("message")
    try:
        # 检查响应
        if response_a.status_code == 200 and message == "success":
            print(f"订单创建成功：邮箱{email}")
        elif response_a.status_code == 500 and message == "代码已存在重复数据":
            print(f"订单{email} 代码{code} 已存在，无法创建")
    except Exception:
        file.write(
            f"{datetime.datetime.now()}:创建订单请求异常：邮箱 {email}，响应消息：{message}\n")


# 创建error.txt文件以追加记录异常信息
with open('error.txt', 'a') as error_file:
    # 遍历xunguo表格的每一行
    for index, row in xunguo_data.iterrows():
        account = row["帐号"]
        password = row["密码"]
        card = row["礼品卡"]
        card_status = row["卡片状态"]
        execution_info = row["执行信息"]

        # 判断卡片状态是否有效
        if card_status != "有效":
            error_file.write(f"{datetime.datetime.now()}: 迅果 表中的 {account}, {card} 卡片状态非有效\n")
            continue

        if not isinstance(card, str):
            error_file.write(f"{datetime.datetime.now()}: 迅果 表中的 {account}, {card} 卡片卡密非法\n")
            continue

        # 使用正则表达式提取面值数据
        value_match = re.search(r'面值：US\$(\d+\.\d+)', execution_info)
        if value_match:
            value = value_match.group(1)
        else:
            error_file.write(f"{datetime.datetime.now()}: {account}, {card} 无法提取面值数据\n")
            continue

        # 在shoukashang表格中查找相关联的数据
        related_rows = shoukashang_data[shoukashang_data["卡密"].str.contains(card, na=False)]

        if related_rows.empty:
            error_file.write(
                f"{datetime.datetime.now()}: 迅果 表中的 {account}, {card} 无法在 收卡商 表中找到对应数据\n")
            continue

        # 遍历匹配的行
        for index, shoukashang_row in related_rows.iterrows():
            if shoukashang_row["状态"] == "Success":
                exchange_rate = shoukashang_row["汇率"]
                operator = shoukashang_row["操作人"]
                # 调用方法，传入所需的参数
                add_mail(account, password, error_file)
                add_order(account, card, value, exchange_rate, operator, error_file)
            else:
                error_file.write(
                    f"{datetime.datetime.now()}: 迅果 表中的 {account}, {card} 对应的 收卡商 表状态非Success------\n")
        time.sleep(1)
